
package com.gogowan.agroenterprise.contorl;

import org.json.JSONException;
import org.json.JSONObject;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.UpdateActivity;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.model.JumpTable;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.Version;
import com.gogowan.agroenterprise.model.VersionClientInfo;
import com.gogowan.agroenterprise.utils.ICodeUtils;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.widget.Toast;

/**
 * 检查更新
 * @author zk
 *
 */
public class CheckUpdateAsync extends MyAsyncTask {
	private BaseActivity activity;
	/**
	 * 升级网址
	 */
	private String updateUrl;
	/**
	 * 是否强制更新
	 */
	private int isforceupdate;
    /**
     * 是否初始化更新
     */
    private boolean isInitUpdate=true;
    /**
     * 网址
     */
    private String url;
	public CheckUpdateAsync(BaseActivity activity)
	{
		this.isInitUpdate=false;
		this.activity=activity;
		url=activity.getString(R.string.update_url);
	}
	public CheckUpdateAsync(BaseActivity activity,boolean isInitUpdate)
	{
		this.activity=activity;
		this.isInitUpdate=isInitUpdate;
		url=activity.getString(R.string.update_url);
	}
	@Override
	protected void onPostExecute(Object res) {
		/*
		 * 此方法在主线程执行，任务执行的结果作为此方法的参数返回
		 */
		if (activity.getState()) {
			return;
		}
		String results = (String) res;
		if (results.equals("") || results == null) {
			if(!isInitUpdate){
				activity.showToast("与服务器通讯失败!");
			}
			return;
		}
		Message message = activity.stringToMessage(results);// 转换成消息盒子
		if (message == null) {
			if(!isInitUpdate){
				activity.showToast("与服务器通讯失败!");
			}
			return;
		}
		int result = 0;
		String resultinfo = "";
		String describe = "";
		JSONObject json = null;
		CharSequence charseq = null;
		try {
			String content = message.getMessagebody().getContent();
			json = new JSONObject(content);
			result = json.optInt("result");
			resultinfo = json.optString("resultinfo");
			String des = json.optString("describe");
			charseq = Html.fromHtml(des);
			// charseq=Html.fromHtml(des);
			// des=charseq.toString();
			// String[] des2=des.split(";");
			// for (int i = 0; i < des2.length; i++) {
			// describe+=des2[i]+"\n";
			// }
			// describe="<font color='red'>版本信息</font>：;1.添加自动更新功能;2.在线同步通讯录功能;3.添加I码书签功能";
		} catch (JSONException e) {
			// TODO: handle exception
			Log.e("e=", e.toString());
		}

		JumpTable jumpTable=new JumpTable();
		jumpTable=(JumpTable)ICodeUtils.fromJSON(json.toString(), JumpTable.class);
		
		if(jumpTable==null){
			return;
		}
		//保存跳转解析
		//activity.getBMSApplication().setJumpTable(jumpTable);
		
		if (result == 1810) {
			updateUrl = jumpTable.getUrl().trim();
			isforceupdate = jumpTable.getIsforceupdate();
		if (updateUrl.equals("0") || updateUrl.equals("")
				|| updateUrl.equals("null")) {
			// SkipActivity(Main.this,true);
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(activity);
			builder.setTitle("升级");

			builder.setMessage(charseq);
			builder.setCancelable(false);// 是否可以按BACK键
			builder.setPositiveButton("是", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub

					Intent intent = new Intent();
					intent.setClass(activity, UpdateActivity.class);
					Bundle mBundle = new Bundle();
					mBundle.putSerializable("token", new String[] {
							updateUrl, "" + isforceupdate, "" });
					intent.putExtras(mBundle);
					activity.startActivity(intent);
					activity.finish();
				}
			});
			if (isforceupdate!=1)// 非强制升级
			{
				builder.setNegativeButton("否", new OnClickListener() {
					public void onClick(DialogInterface dialog,
							int whichButton) {
						// do nothing
						// SkipActivity(UpdateActivity.this, true);
					}
				});
			}
			builder.create().show();
		}
	} else if (result == -1810 && !isInitUpdate) {
		activity.ShowDialog("提示", resultinfo);
	}
		if (isInitUpdate) {
			isInitUpdate = false;
		}
		super.onPostExecute(result);
	}

	@Override
	protected Object doInBackground(Object... params) {
		CodeUpdate update = new CodeUpdate();
		update.setUrl(url);
		VersionClientInfo versioninfo = new VersionClientInfo();
		try {
			versioninfo.setVersioncode(Integer
					.parseInt(activity.getString(R.string.version_code)));
		} catch (NumberFormatException efe) {
			versioninfo.setVersioncode(0);
		}
		versioninfo.setVersion(ICodeUtils.getVersionName(activity));// getString(R.string.version));
		Version result = update.getUpdateInfo(versioninfo);// 提交检查版本

		return update.getResult();
	}

}